package com.sgb.kjwl.view.widget.self

import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import com.sgb.kjwl.R


/**
 * Created by tdd on 2018/6/14.
 */
open class FixProportionImageView : androidx.appcompat.widget.AppCompatImageView {
    private var propertion = 0f

    constructor(context: Context) : super(context) {}

    @JvmOverloads constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) {
        val array = context.obtainStyledAttributes(attrs, R.styleable.FixProportionImageView)
        propertion = array.getFloat(R.styleable.FixProportionImageView_proportion, 0f)
        array.recycle()
    }

    fun setPropertion(propertion: Float) {
        this.propertion = propertion
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (propertion == 0f) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
            return
        }
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = (width / propertion).toInt()
        setMeasuredDimension(width, height)
    }
}
